<script lang="ts" setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import jyglService from '@/api/jygl'
import xtpzService from '@/api/xtpz'
import {
  JyspdspListQueryResult,
  JysqajxxlbQueryResult,
  JysqspdalbQueryResult,
} from '@/api/jygl-dto'
import formBox from '@/components/queryTable/form/index.vue'
import tableBox from '@/components/queryTable/table/index.vue'
import { formItems } from '../form-item'
import { TableItem } from '@/api/common'
import spthDialog from '../dialogs/spth.vue'
import lcgzDialog from '@/views/daly/jygl/dialogs/lcgz-dialog.vue'
import jydDialog from '@/views/daly/jygl/dialogs/jyd-dialog.vue'
import TreeUtilDTO from '@/utils/tree'
const emit = defineEmits(['addTab'])
// loading
const loading = ref<boolean>(false)
const formLabel = ref()
// 入参
const rightSmall = ref<boolean>(true)

const dragFlag = ref<boolean>(false)
const moveLenHeight = ref<number>(0)
const props = defineProps({
  activeName: {
    type: String,
    defalut: '',
  },
})

watch(
  () => props.activeName,
  (val) => {
    if (val === 'dsp') {
      changePageNum(1)
    }
  },
)
/**
 * 数据源
 */
const optionsObjs = ref<any>({})

// 生命周期
onMounted(async () => {
  loading.value = true
  queryDlrsjqx()
  formLabel.value = await formItems('dsp')
  loading.value = false
  // 分页
  changePageNum(1)
})

const queryDlrsjqx = () => {
  xtpzService.getDlrsjqx({}).then((res: any) => {
    optionsObjs.value.sjdwbms = TreeUtilDTO.getTreeData(
      (res.data.sqdwxxList || []).map((el: any) => ({
        ...el,
        mc: el.dwmc,
        dm: el.dwbm,
        fdm: el.fdwbm,
      })),
      'dwbm',
      'fdwbm',
    )
  })
}

const total = ref<number>(0)
const page = computed(() => {
  return {
    pageNum: form.value.pageNum,
    pageSize: form.value.pageSize,
    total: total.value,
  }
})
/*
 * 分页
 */
const changePageNum = (val: number) => {
  form.value.pageNum = val
  queryTable()
}

/*
 * 分页
 */
const changePageSize = (val: number) => {
  form.value.pageNum = 1
  form.value.pageSize = val
  queryTable()
}

/*
 * 查询按钮
 */
const searchTable = (data: any) => {
  const newObj: any = {}
  for (const key in data) {
    if (key.endsWith('-rq')) {
      if (data[key]?.length) {
        newObj['sqrqStart'] = data[key][0]
        newObj['sqrqEnd'] = data[key][1]
      } else {
        newObj['sqrqStart'] = ''
        newObj['sqrqEnd'] = ''
      }
    }
    newObj[key] = data[key]
  }
  form.value.filter = newObj
  queryTable()
}

/*
 * 获取表格数据
 */
// 借阅审批-待审批查询条件
const form = ref({
  pageNum: 1, // 页码
  pageSize: 20, // 页容量
  filter: {
    jydalxdm: '',
    jydbh: '',
    jyfsdm: '',
    jylxdm: '',
    jymddm: '',
    jymx: '',
    jyrxm: '',
    sjdwbms: [],
    sqrqEnd: '',
    sqrqStart: '',
  }, // 过滤Dto对象
})

/*
 * 获取表格数据
 */
const tableBoxRef = ref<InstanceType<typeof tableBox>>()
// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '借阅单编号',
      prop: 'jydbh',
      width: 220,
      dqfs: 'left',
    },
    { label: '申请日期', prop: 'sqrq', width: 120, dqfs: 'left' },
    { label: '借阅单位/部门', prop: 'jydw', width: 160, dqfs: 'left' },
    { label: '借阅人', prop: 'jyrxm', width: 120, dqfs: 'left' },
    { label: '借阅人电话', prop: 'jyrdh', width: 160, dqfs: 'left' },
    { label: '档案所属院', prop: 'sjdwmc', width: 160, dqfs: 'left' },
    { label: '档案类型', prop: 'jydalxmc', width: 120, dqfs: 'left' },
    { label: '借阅类型', prop: 'jylxmc', width: 120, dqfs: 'left' },
    { label: '借阅方式', prop: 'jyfsmc', width: 120, dqfs: 'left' },
    { label: '借阅目的', prop: 'jymdmc', width: 120, dqfs: 'left' },
    { label: '借阅明细', prop: 'jymx', width: null, dqfs: 'left' },
  ],
})

// 借阅审批-未审批列表
const queryTable = () => {
  const params = form.value
  jyglService
    .queryJyspdspList(params)
    .then((res) => {
      tableData.value.data = res.data.list
      total.value = res.data.total
      ssdaList.value = []
      spdaList.value = []
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/**
 * 表格选择
 */
const selectRow = ref<JyspdspListQueryResult>()
const selectionChange = (val: JyspdspListQueryResult[], row: any) => {
  if (val.length > 0) selectRow.value = row
  else selectRow.value = undefined
  if (val.length > 1) {
    const delChecked = val.shift()
    tableBoxRef.value?.refTable.toggleRowSelection(delChecked, false)
  }
}
const selectAllChange = () => {
  nextTick(() => {
    if (selectRow.value) {
      selectRow.value = undefined
      tableBoxRef.value?.refTable.clearSelection()
    } else {
      selectRow.value = tableData.value.data[0]
      tableBoxRef.value?.refTable.clearSelection()
      tableBoxRef.value?.refTable.toggleRowSelection(selectRow.value, true)
    }
  })
}

/*
 * 打开流程跟踪弹窗
 */
const lcgzRef = ref()
const viewLcgz = (row: any) => {
  lcgzRef.value?.openDialog(row)
}

/*
 * 打开借阅单弹窗
 */
const jydRef = ref()
const viewJyd = (row: any) => {
  jydRef.value?.openDialog(row.jysqbh)
}

/*
 * 审批通过
 */
const sptg = () => {
  ElMessageBox.confirm('是否通过', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = {
      jylcdm: '',
      jysqbh: selectRow.value!.jysqbh,
      shjgdm: 'gd0470001',
      shjgmc: '通过',
      thyy: '',
    }
    jyglService
      .saveJyShjg(params)
      .then(() => {
        queryTable()
        ElMessage({ type: 'success', message: '操作成功' })
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

/*
 * 审批退回(打开退回弹窗)
 */
const spthRef = ref()
const openSpth = () => {
  spthRef.value.openDialog(selectRow.value)
}

/*
 * 拖拽事件
 */
// 初始距离
// 是否按下
const dragstart = () => {
  dragFlag.value = true
}
const dragRight = (e: any) => {
  if (!dragFlag.value || !e.clientY) {
    return
  }
  if (e.clientY && window.innerHeight - e.clientY - 26 <= 200) {
    moveLenHeight.value = 200
  } else if (e.clientY && window.innerHeight - e.clientY - 26 >= 300) {
    moveLenHeight.value = 300
  } else {
    moveLenHeight.value = window.innerHeight - e.clientY - 26
  }
}
const dragend = () => {
  dragFlag.value = false
}
/**
 * 借阅单关联的档案
 */
// 档案类型
const activeDalx = ref('ssda')

const ssdaTableHeader = [
  {
    label: '档号',
    prop: 'ajdh',
    width: 200,
    custom: true,
    dqfs: 'left',
  },
  { label: '案件名称', prop: 'ajmc', width: 100, dqfs: 'left' },
  { label: '部门受案号', prop: 'bmsah', width: 300, dqfs: 'left' },
  { label: '当事人', prop: 'dsrmc', width: 120, dqfs: 'left' },
  { label: '案由', prop: 'aymc', width: null, dqfs: 'left' },
  { label: '检察官', prop: 'cbjcg', width: 120, dqfs: 'left' },
  { label: '立卷单位', prop: 'cbdwmc', width: 200, dqfs: 'left' },
  { label: '归档日期', prop: 'gdrq', width: 120, dqfs: 'left' },
  { label: '文件页数', prop: 'zzajys', width: 120, dqfs: 'left' },
]

const spdaTableHeader = [
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    custom: true,
    sort: true,
    dqfs: 'left',
  },
  { label: '立卷单位', prop: 'ljdw', width: 200, dqfs: 'left' },
  { label: '归档年度', prop: 'gdnd', width: 120, dqfs: 'left' },
  { label: '保管期限', prop: 'bgqx', width: 120, dqfs: 'left' },
  { label: '密级', prop: 'mj', width: 120, dqfs: 'left' },
  { label: '题名', prop: 'tm', width: 120, dqfs: 'left' },
  { label: '视频类型', prop: 'splx', width: 120, dqfs: 'left' },
  { label: '录制者', prop: 'lzz', width: 120, dqfs: 'left' },
  {
    label: '录制日期',
    prop: 'lzrq',
    width: 160,
    dqfs: 'left',
    format: 'YYYY-MM-DD',
  },
]

/*
 * 查看借阅单下的诉讼档案
 */
const ssdaList = ref<JysqajxxlbQueryResult[]>([])
const querySsdaList = (row: JyspdspListQueryResult) => {
  const params = { jysqbh: row.jysqbh }
  jyglService
    .queryJysqajxxlb(params)
    .then((res) => {
      ssdaList.value = res.data
      nextTick(() => {
        if (ssdaList.value.length) activeDalx.value = 'ssda'
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 查看借阅单下的视频档案
 */
const spdaList = ref<JysqspdalbQueryResult[]>([])
const querySpdaList = (row: JyspdspListQueryResult) => {
  const params = { jysqbh: row.jysqbh }
  jyglService
    .queryJysqspdalb(params)
    .then((res) => {
      spdaList.value = res.data
      nextTick(() => {
        if (!ssdaList.value.length && spdaList.value.length) activeDalx.value = 'spda'
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const rowClick = (row: JyspdspListQueryResult) => {
  querySsdaList(row)
  querySpdaList(row)
}

// 查看档案详情
const viewDaxq = (row: any) => {
  emit('addTab', {
    ...row,
    fldm: activeDalx.value === 'ssda' ? 1 : 31,
    dalx: activeDalx.value,
    showDownloadPrinting: true,
  })
}
</script>
<template>
  <div class="container">
    <div
      class="right-top"
      :style="{ height: moveLenHeight ? `calc(100% - ${moveLenHeight + 12}px)` : '' }"
    >
      <!--表单-->
      <div class="form-box">
        <form-box
          ref="formBoxRef"
          :formLabel="formLabel"
          :formData="form.filter"
          :moreShow="false"
          :optionsObj="optionsObjs"
          @searchEvent="searchTable"
        />
      </div>
      <div class="btn-box">
        <div class="table-title">
          <span>待审核列表</span>
        </div>
        <button class="btn_operation" :disabled="!selectRow" @click="sptg">
          <div class="btn-shtg"></div>
          审批通过
        </button>
        <button class="btn_operation" :disabled="!selectRow" @click="openSpth">
          <div class="btn-shth"></div>
          审批退回
        </button>
        <button class="btn_operation" @click="changePageNum(1)">
          <div class="btn-refresh"></div>
          刷新
        </button>
      </div>
      <!--表格-->
      <div class="table-box">
        <table-box
          gnbm="daly-dsp"
          ref="tableBoxRef"
          :selectShow="true"
          :table-data="tableData"
          :formParams="form"
          :getTableDataParam="page"
          :tableInfo="{ total: page.total }"
          :highlight-current-row="true"
          @changeCurrent="changePageNum"
          @changeSize="changePageSize"
          @row-click="rowClick"
          @selectChange="selectionChange"
          @select-all-change="selectAllChange"
        >
          <template #myAction>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <div class="active-img" title="流程跟踪" @click="viewLcgz(scope.row)">
                  <img src="@/assets/images/gdgztext.png" />
                </div>
                <div class="active-img" title="借阅单" @click="viewJyd(scope.row)">
                  <img src="@/assets/images/details.png" />
                </div>
              </template>
            </el-table-column>
          </template>
        </table-box>
      </div>
    </div>
    <!--拖动div-->
    <div
      v-if="ssdaList.length || spdaList.length"
      class="table-drag-box"
      :draggable="true"
      title="可上下拖动"
      @dragstart="dragstart()"
      @dragend="dragend()"
      @drag="dragRight($event)"
    >
      <div class="dragImg">
        <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
      </div>
    </div>
    <div
      v-if="ssdaList.length || spdaList.length"
      class="right-bottom"
      :class="{ small: !rightSmall }"
      :style="{ height: moveLenHeight ? `${moveLenHeight}px` : '' }"
    >
      <div class="right-img" @click="rightSmall = !rightSmall">
        <img src="@/assets/images/zsq.png" alt="" v-if="rightSmall" />
        <img src="@/assets/images/ysq.png" alt="" v-else-if="!rightSmall" />
      </div>
      <el-tabs class="dsp-tabs" v-model="activeDalx">
        <el-tab-pane
          v-if="ssdaList.length"
          label="&nbsp;&nbsp;&nbsp;&nbsp;诉讼档案&nbsp;&nbsp;&nbsp;&nbsp;"
          name="ssda"
          lazy
        >
        </el-tab-pane>
        <el-tab-pane
          v-if="spdaList.length"
          label="&nbsp;&nbsp;&nbsp;&nbsp;视频档案&nbsp;&nbsp;&nbsp;&nbsp;"
          name="spda"
          lazy
        >
        </el-tab-pane>
      </el-tabs>
      <div class="da-table">
        <el-table
          :data="activeDalx === 'ssda' ? ssdaList : spdaList"
          stripe
          row-key="id"
          height="100%"
        >
          <el-table-column
            v-for="item in activeDalx === 'ssda' ? ssdaTableHeader : spdaTableHeader"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :min-width="item.width"
            show-overflow-tooltip
            :align="item.dqfs || 'left'"
          >
            <template #default="scope">
              <div v-if="item.custom">
                <el-link
                  type="primary"
                  class="custom-link"
                  :underline="false"
                  @click="viewDaxq(scope.row)"
                  >{{ scope.row[item.prop] }}</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 审批退回 -->
    <spthDialog ref="spthRef" @refresh="queryTable"></spthDialog>
    <!-- 流程跟踪 -->
    <lcgzDialog ref="lcgzRef" />
    <!-- 借阅单 -->
    <jydDialog ref="jydRef" />
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .right-top {
    flex: 1;
    height: calc(100% - 212px);
    width: 100%;
    .form-box {
      width: 100%;
      text-align: right;
    }
    .btn-box {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-bottom: 10px;
    }
    .table-box {
      height: calc(100% - 140px);
    }
    .container {
      flex-direction: column;
    }
  }
  .right-bottom {
    height: 200px;
    position: relative;
    overflow-y: auto;
    &.small {
      height: 16px !important;
      border: none !important;
      .da-table,
      .dsp-tabs {
        display: none;
      }
    }
    .right-img {
      z-index: 9;
      cursor: pointer;
      position: absolute;
      left: calc(50% - 4px);
      top: -24px;
      transform: rotate(-90deg);
    }
    .dsp-tabs {
      height: auto;
      border: 0;
      :deep(.el-tabs__content) {
        height: 0;
        padding: 0;
      }
      :deep(.el-tabs__item) {
        height: 36px;
        padding: 0;
        &:hover,
        &.is-active {
          background-color: transparent;
        }
      }
    }
    .da-table {
      height: calc(100% - 43px);
      padding: 16px 0;
    }
  }
}

.table-drag-box {
  margin-top: 10px;
  flex-shrink: 0;
  height: 13px;
  width: 100%;
  cursor: row-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  border-top: 1px solid #dae4f1;
  border-bottom: 1px solid #dae4f1;
  .dragImg {
    height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
    }
  }
}
.active-img {
  cursor: pointer;
  float: left;
}
.active-img + .active-img {
  margin-left: 10px;
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  border-right: none !important;
  color: #0090ff;
  background-color: #d9edff;
}
</style>
